﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using IBS.Model;
using IBS.ServiceContracts;

namespace IBS.Bll.AutoPayments
{
    public class AutoPaymentProcessor
    {
        private const int TimeInterval =  60/2  * 1000;
        private ManualResetEvent checkEvent;
        private IAutoPaymentService _autoPaymentService;
        private readonly ITransferService _transferService;

        public AutoPaymentProcessor(IAutoPaymentService autoPaymentService, ITransferService transferService)
        {
            _autoPaymentService = autoPaymentService;
            _transferService = transferService;
            checkEvent = new ManualResetEvent(false);
            thread = new Thread(ProcessCheck);
            thread.IsBackground = true;
            thread.Start();
            checkEvent.Set();
        }
        private DateTime lastCheck = DateTime.MinValue;
        private Thread thread;


        public IList<AutoPayment> GetActualAutoPayments(DateTime currentTime)
        {
            IList<AutoPayment> result = null;

            var autoPayments = new List<AutoPayment>();

            var checkDatePayments = lastCheck.Minute < currentTime.Minute;
            lastCheck = currentTime;
            if (checkDatePayments)
            {
                var test = _autoPaymentService.GetAutoPaymentById(7).DayOfMonth;
                var datePayments = _autoPaymentService.GetAutoPayments(p =>
                       p.Card != null  && !p.Card.isDeleted   &&                    
                        p.DayOfMonth != null && (p.DayOfMonth == currentTime.Minute)
                    );
                autoPayments.AddRange(datePayments);
            }

            result = autoPayments;

            return result;
        }

        private void ProcessCheck()
        {
            while (checkEvent.WaitOne(TimeInterval))
            {
                ForcePayAutoPayments();
            }
        }

        public void ForcePayAutoPayments()
        {
            var autoPayments = GetActualAutoPayments(DateTime.Now);
            if (autoPayments != null && autoPayments.Count > 0)
            {
                foreach (var p in autoPayments)
                {
                    PayAutoPayment(p.Card, p, p.PaymentDetail, p.ISO, p.Amount);
                }
            }
        }

        private void PayAutoPayment(Card fromCard, AutoPayment toAutoPayment, string paymentDetail, string ISO, decimal amount)
        {
            _transferService.PayAutoPayment(fromCard, toAutoPayment, paymentDetail, ISO, amount);
        }
        
    }
}
